<template>
  <div class="sign--box">
    <a-config-provider :locale="locale">
      <a-upload
        v-decorator="['sign']"
        list-type="picture-card"
        :customRequest="onCustomRequest"
        :file-list="getFileList()"
        @preview="handlePreview"
        @change="change"
        :before-upload="beforeUpload"
      >
        <a-button> <a-icon type="upload" />点击上传</a-button>
        <div class="upload--word--box">
          <span class="upload--word">支持格式:jpg/png</span>
          <span class="upload--word">支持大小:小于200KB</span>
        </div>
      </a-upload>
    </a-config-provider>

    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="previewVisible = false"
    >
      <img
        alt="example"
        style="width: 100%"
        :src="previewImage"
        v-if="previewVisible"
      />
    </a-modal>
  </div>
</template>

<script>
import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
import { mapState } from "vuex";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  name: "Myupload",
  props: ["sign", "imgServerUrl", "userId"],
  data() {
    return {
      previewVisible: false,
      previewImage: "",
      locale: zhCN,
    };
  },
  computed: {
    ...mapState(["SERVERBASE_URL"]),
  },
  methods: {
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("上传格式错误!");
      }
      const isLt2M = file.size / 1024 < 200;
      if (!isLt2M) {
        this.$message.error("图片大小超过最大限制!");
      }
      return isJpgOrPng && isLt2M;
    },

    //自定义上传
    async onCustomRequest(info) {
      try {
        const data = new FormData();
        data.append(info.filename, info.file);
        const server_request = new Request(
          `${this.imgServerUrl}/api/upload/${this.userId}`,
          {
            method: "POST",
            body: data,
          }
        );
        const server_resp = await fetch(server_request).then((res) =>
          res.json()
        );
        if (server_resp.code === 200) {
          this.$emit("on-change", server_resp.data);
          this.$message.success("上传成功!");
          console.log("签名地址", server_resp.data);
        } else {
          const request = new Request(`${this.SERVERBASE_URL}/api/upload`, {
            method: "POST",
            body: data,
          });
          const resp = await fetch(request).then((res) => res.json());
          if (resp.status === "ok") {
            this.$emit("on-change", resp.data);
            this.$message.success("上传成功!");
            console.log("签名地址", resp.data);
          } else {
            this.$message.error(`上传失败,${resp.msg}`);
          }
        }
      } catch (error) {
        console.log("上传用户电子签名 error", error);
      }
    },

    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },

    getFileList() {
      let result = null;
      if (this.sign) {
        result = [
          {
            uid: Math.random().toString(36).slice(-6),
            name: Math.random().toString(36).slice(-6),
            url: this.sign,
          },
        ];
      } else {
        result = [];
      }
      return result;
    },

    change(data) {
      console.log("change", data);
      if (data.fileList.length == 0) {
        console.log("删除图片");
        this.$emit("on-change", "");
      }
    },
  },
};
</script>

<style scoped>
.upload--word--box {
  display: flex;
  flex-direction: column;
}
.upload--word {
  font-size: 12px;
  text-align: left;
}
</style>
